<?php
class PostService {
	public $dbutil;
	function __construct($dbutil) {
		$this->dbutil = $dbutil;
	}
 
	public function getComments($postid) {
		$sql = " SELECT  @rownum:=@rownum+1 AS rownum,p.*,u.user_photo,u.username FROM (SELECT @rownum:=0) r,post_comments p LEFT join users u on p.user_id = u.userid WHERE  comment_approved = 0 and comment_post_ID='" . $postid . "'   order by p.comment_date asc";
		return $this->dbutil->get_results ( $sql );
	}

	public function getnewComments($postid) {
		$sql = " SELECT  @rownum:=@rownum+1 AS rownum,p.*,u.user_photo,u.username FROM (SELECT @rownum:=0) r,post_comments p LEFT join users u on p.user_id = u.userid WHERE  comment_approved = 0 and comment_post_ID='" . $postid . "'   order by p.comment_date desc LIMIT 3";
		return $this->dbutil->get_results ( $sql );
	}
	
	public function savePostComments($sql) {
		return	$this->dbutil->query($sql);
	}
	public function updateAgreeCounts($postid) {
		$sqlquery = "select agree_count from  posts  where  id= '" . $postid . "'";
		$item = $this->dbutil->get_results ( $sqlquery );
		$agree = $item[0]->agree_count;
		if(empty($agree)){
			$agree = 1;
		}else{
			$agree +=1;
		}
		$sql = "UPDATE posts SET agree_count = ".$agree." where  id= '" . $postid . "'";
		 $this->dbutil->get_results ( $sql );
		return self::getPost($postid);
	}
    public function getAgreeCounts($postid) {
        $sqlquery = "select agree_count from  posts  where  id= '" . $postid . "'";
        $item = $this->dbutil->get_results ( $sqlquery );
        $agree = $item[0]->agree_count;
        if(empty($agree)){
            $agree = 0;
        }

        return $agree;
    }
	public function updateViewCounts($postid) {
		$sqlquery = "select click_count from  posts  where  id= '" . $postid . "'";
		$item = $this->dbutil->get_results ( $sqlquery );
		$agree = $item[0]->click_count;
		if(empty($agree)){
			$agree = 1;
		}else{
			$agree +=1;
		}
		$sql = "UPDATE posts SET click_count = ".$agree." where  id= '" . $postid . "'";
		 $this->dbutil->get_results ( $sql );

         return $agree;
	}
	public function getPost($postid) {
		$sql = "SELECT  p.*,u.user_name username FROM posts p LEFT join admin_users u on p.post_author = u.id WHERE  p.id= '" . $postid . "'";
		return $this->dbutil->get_results ( $sql );
	}
	public function getPrePost($postid) {
		$sql = "SELECT  * FROM posts WHERE  id <'" . $postid . "' ORDER BY id DESC LIMIT 1   ";
		return $this->dbutil->get_results ( $sql );
	}
	public function getNxtPost($postid) {
		$sql = "SELECT  * FROM posts WHERE  id > '" . $postid . "' ORDER BY id ASC LIMIT 1   ";
		return $this->dbutil->get_results ( $sql );
	}
	public function getTagIdByName($postid) {
		$sql = "SELECT pt.*,tg.tag_name FROM post_tag pt LEFT JOIN tags tg ON pt.tag_id = tg.tag_id WHERE pt.post_id= '".$postid."'";
		return $this->dbutil->get_results ( $sql );
	}
	
}
